"""
家庭成员相关的异步 API 路由
"""

from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, EmailStr
from sqlalchemy.ext.asyncio import AsyncSession

from src.auth import require_admin, require_child, require_guest
from src.crud import family_crud
from src.database import get_db
from src.models.family_model import FamilyMember, FamilyRelationship, FamilyRole
from src.security import get_password_hash


# Pydantic 模型
class FamilyMemberBase(BaseModel):
    username: str
    email: EmailStr
    full_name: str


class FamilyMemberCreate(FamilyMemberBase):
    password: str
    role: FamilyRole | None = FamilyRole.MEMBER
    relationship: FamilyRelationship | None = None
    phone: str | None = None
    birth_date: datetime | None = None
    gender: str | None = None
    nickname: str | None = None


class FamilyMemberUpdate(BaseModel):
    username: str | None = None
    email: EmailStr | None = None
    full_name: str | None = None
    nickname: str | None = None
    role: FamilyRole | None = None
    relationship: FamilyRelationship | None = None
    family_id: str | None = None
    phone: str | None = None
    avatar: str | None = None
    birth_date: datetime | None = None
    gender: str | None = None
    is_active: bool | None = None


class FamilyMemberResponse(FamilyMemberBase):
    id: int
    is_active: bool
    nickname: str | None = None
    role: FamilyRole
    relationship: FamilyRelationship | None = None
    family_id: int
    phone: str | None = None
    avatar: str | None = None
    birth_date: datetime | None = None
    gender: str | None = None
    created_at: datetime
    family_name: str | None = None

    model_config = {"from_attributes": True}


# 创建路由器
router = APIRouter(tags=["family"])


@router.post(
    "/family-members/",
    response_model=FamilyMemberResponse,
    status_code=status.HTTP_201_CREATED,
)
async def create_family_member(
    member: FamilyMemberCreate,
    db: AsyncSession = Depends(get_db),
    current_user: FamilyMember = Depends(require_admin),
):
    """创建家庭成员 - 需要成员管理员权限"""
    # 检查用户名是否已存在
    existing_member = await family_crud.get_family_member_by_username(
        db, member.username
    )
    if existing_member:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Username already registered",
        )

    # 检查邮箱是否已存在
    existing_email = await family_crud.get_family_member_by_email(db, member.email)
    if existing_email:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered"
        )

    # 创建家庭成员(密码应该是加密的,这里简化处理)
    created_member = await family_crud.create_family_member(
        db=db,
        username=member.username,
        email=member.email,
        hashed_password=get_password_hash(member.password),  # 实际应用中应该加密
        full_name=member.full_name,
        role=member.role or FamilyRole.MEMBER,
        relationship=member.relationship,
        family_id=current_user.family_id,
        phone=member.phone,
        birth_date=member.birth_date,
        gender=member.gender,
        nickname=member.nickname,
    )
    return created_member


@router.get("/family-members/", response_model=list[FamilyMemberResponse])
async def get_family_members(
    skip: int = 0,
    limit: int = 100,
    role: FamilyRole | None = Query(None, description="角色筛选"),
    db: AsyncSession = Depends(get_db),
    current_user: FamilyMember = Depends(require_child),
):
    """获取家庭成员列表 - 需要成员读取权限"""

    # 如果指定了家庭ID,验证用户是否有权访问该家庭
    if role:
        members = await family_crud.get_family_members_by_role(
            db, role, current_user.family_id
        )
    else:
        members = await family_crud.get_family_members(
            db, skip=skip, limit=limit, family_id=current_user.family_id
        )
    return members


@router.get("/family-members/{member_id}", response_model=FamilyMemberResponse)
async def get_family_member(
    member_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: FamilyMember = Depends(require_child),
):
    """获取单个家庭成员 - 需要成员读取权限"""
    member = await family_crud.get_family_member_by_id(db, member_id)
    if not member:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Family member not found"
        )
    return member


@router.put("/family-members/{member_id}", response_model=FamilyMemberResponse)
async def update_family_member(
    member_id: int,
    member_update: FamilyMemberUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: FamilyMember = Depends(require_admin),
):
    """更新家庭成员 - 需要成员写入权限"""

    # 获取要更新的成员信息
    target_member = await family_crud.get_family_member_by_id(db, member_id)
    if not target_member:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Family member not found"
        )

    # 如果要修改角色,需要管理员权限
    if member_update.role is not None:
        target_role = (
            FamilyRole(target_member.role.value)
            if hasattr(target_member.role, "value")
            else target_member.role
        )
        if member_update.role != target_role:
            user_role = (
                FamilyRole(current_user.role.value)
                if hasattr(current_user.role, "value")
                else current_user.role
            )
            if user_role != FamilyRole.ADMIN:
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="权限不足,只有管理员可以修改角色",
                )
    # 过滤掉 None 值
    update_data = {k: v for k, v in member_update.model_dump().items() if v is not None}

    updated_member = await family_crud.update_family_member(
        db, member_id, current_user.family_id, **update_data
    )
    if not updated_member:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Family member not found"
        )
    return updated_member


@router.delete("/family-members/{member_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_family_member(
    member_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: FamilyMember = Depends(require_admin),
):
    """删除家庭成员 - 需要成员管理员权限"""

    # 获取要删除的成员信息
    target_member = await family_crud.get_family_member_by_id(db, member_id)
    if not target_member:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Family member not found"
        )

    # 不能删除自己
    if target_member.id == current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="不能删除自己的账户"
        )
    deleted = await family_crud.delete_family_member(
        db, member_id, current_user.family_id
    )
    if not deleted:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Family member not found"
        )


@router.get("/family-members/{member_id}/is-admin", response_model=dict)
async def check_is_admin(
    member_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: FamilyMember = Depends(require_guest),
):
    """检查是否为家庭管理员 - 需要成员读取权限"""

    # 验证用户是否有权访问该家庭
    is_admin = await family_crud.is_family_admin(db, member_id, current_user.family_id)
    return {"is_admin": is_admin}


@router.get("/families/admins", response_model=list[FamilyMemberResponse])
async def get_family_admins(
    db: AsyncSession = Depends(get_db),
    current_user: FamilyMember = Depends(require_child),
):
    """获取家庭管理员列表 - 需要成员读取权限"""

    # 验证用户是否有权访问该家庭
    admins = await family_crud.get_family_admins(db, current_user.family_id)
    return admins
